/*
 * moodLamp.c
 *
 * Created: 9/16/2013 12:38:06 AM
 *  Author: Tim
 */ 

#include <stdlib.h>
#include "../src/Epiphany.h" 

volatile uint32_t milliseconds = 0;
float delayLength = 100;


struct
{
	
	uint16_t R_current;
	uint16_t R_new;
	
	uint16_t G_current;
	uint16_t G_new;
	
	uint16_t B_current;
	uint16_t B_new;
	
}led;

void setup()
{
	clockInit();
	
	TCE0.PER = 1024;
	TCE0.CTRLA = TC_CLKSEL_DIV1_gc;
	TCE0.CTRLB = TC0_CCAEN_bm | TC0_CCBEN_bm | TC0_CCCEN_bm | TC_WGMODE_SS_gc;
	
	TCD0.CTRLA = TC_CLKSEL_DIV256_gc;
	TCD0.PER = 1024;
	TCD0.CTRLB = TC_WGMODE_SS_gc;
	
		
	adcInit();
	
	PORTE.DIRSET = 0x7;

	sei();
	srand(analogRead(0));

	led.R_current = 1024;
	led.G_current = 1024;
	led.B_current = 1024;
	
	TCE0.CCA = 0;
	TCE0.CCB = 0;
	TCE0.CCC = 0;
	
	
	TCD0.CNT = 0;
	TCD0.INTCTRLA = TC_OVFINTLVL_MED_gc;
	PMIC.CTRL |= PMIC_MEDLVLEN_bm;
}
	
void loop()
{
	srand(analogRead(0));
	led.R_new = rand() & 0x3FF;
	
	if(led.R_current < led.R_new)
	{
		
		milliseconds = 0;
		
		while(led.R_current + milliseconds < led.R_new)
		{
			TCE0.CCA = led.R_current + milliseconds;
		}
		
	}
	else
	{
		
		milliseconds = 0;
		
		while(led.R_current - milliseconds > led.R_new)
		{
			TCE0.CCA = led.R_current - milliseconds;
		}
		
	}
	led.R_current = led.R_new;
	TCE0.CCA = led.R_new;
	
	srand(analogRead(0));
	led.G_new = rand() & 0x3FF;
	
	if(led.G_current < led.G_new)
	{
		
		milliseconds = 0;
		
		while(led.G_current + milliseconds < led.G_new)
		{
			TCE0.CCB = led.G_current + milliseconds;
		}
		
	}
	else
	{
		
		milliseconds = 0;
		
		while(led.G_current - milliseconds > led.G_new)
		{
			TCE0.CCB = led.G_current - milliseconds;
		}
		
	}
	
	led.G_current = led.G_new;
	TCE0.CCB = led.G_new;
	
	srand(analogRead(0));
	led.B_new = rand() & 0x3FF;
	
	if(led.B_current < led.B_new)
	{
		
		milliseconds = 0;
		
		while(led.B_current + milliseconds < led.B_new)
		{
			TCE0.CCC = led.B_current + milliseconds;
		}
		
	}
	else
	{
		
		milliseconds = 0;
		
		while(led.B_current - milliseconds > led.B_new)
		{
			TCE0.CCC = led.B_current - milliseconds;
		}
		
	}
	
	led.B_current = led.B_new;
	TCE0.CCC = led.B_new;
	
}	

ISR(TCD0_OVF_vect)
{
	
	milliseconds++;
	
}